import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.ExcelUtils;
import com.yt.common.utils.StrUtils;
import com.yt.common.utils.TableStructureExportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.yt.phone.models.service.IPhoneBillService;
import com.yt.phone.models.bo.PhoneBillSaveBO;
import com.yt.phone.models.bo.PhoneBillBO;
import com.yt.phone.models.dto.PhoneBillDTO;

/**
 * 用户账单信息联表控制器
 *
 * @author lizicong
 * @Date 2025-11-05 23:17:03
 */

@RestController
@RequestMapping("/cms/phoneBill")
@Slf4j
@Api(value = "PhoneBillController",tags = "用户账单信息联表接口")
public class PhoneBillController {

    @DubboReference
    private IPhoneBillService phoneBillService;
    
    @Autowired
    private TableStructureExportUtils tableStructureExportUtils;

    @ApiOperation(value = "添加用户账单信息联表",notes = "添加用户账单信息联表")
    @PostMapping(value = "/insert")
    public Result insert(PhoneBillSaveBO saveBO) {
        boolean flag = phoneBillService.add(saveBO);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存用户账单信息联表",notes = "保存用户账单信息联表")
    public Result save(PhoneBillSaveBO saveBO){
        if(saveBO.getId() == null){
            //添加
            return  insert(saveBO);
        } else {
            return  update(saveBO);
        }
    }

    @ApiOperation(value = "修改用户账单信息联表",notes = "修改用户账单信息联表")
    @PostMapping("/update")
    public Result update(PhoneBillSaveBO saveBO){
        PhoneBillDTO dto = new PhoneBillDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        boolean flag = phoneBillService.updateById(dto);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }


    @ApiOperation(value = "删除用户账单信息联表",notes = "删除用户账单信息联表")
    @ApiImplicitParam(name = "id",value = "用户账单信息联表id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        boolean flag = phoneBillService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除用户账单信息联表",notes = "批量删除用户账单信息联表")
    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids){
        if(StrUtils.isEmpty(ids)){
            return new Result(CodeEnum.FAIL_100002 );
        }
        String[] arr = ids.split(",");
        phoneBillService.deleteBatchIds(Arrays.asList(arr));
        return new Result<>();
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<PhoneBillDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        PhoneBillDTO dto = phoneBillService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "用户账单信息联表列表",notes = "用户账单信息联表列表")
    @PostMapping("/queryPageList")
    public Result<Page<PhoneBillDTO>> queryPageList(PhoneBillBO bo){
        Wrapper<PhoneBillDTO> wrapper = new EntityWrapper<>();


        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<PhoneBillDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = phoneBillService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    
    @ApiOperation(value = "导出用户账单Excel模板", notes = "导出用户账单Excel模板")
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        try {
            // 使用ExcelUtils导出模板，确保创建表头
            List<PhoneBillSaveBO> list = new ArrayList<>();
            ExcelUtils.exportExcel(list, "用户账单信息模板", "用户账单信息", PhoneBillSaveBO.class, "用户账单信息模板.xls", true, response);
        } catch (Exception e) {
            log.error("导出用户账单Excel模板失败", e);
            try {
                // 如果ExcelUtils导出失败，尝试使用简单的方法创建Excel文件
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("用户账单信息模板.xls", "utf-8"));
                
                // 创建简单的Excel文件
                org.apache.poi.hssf.usermodel.HSSFWorkbook workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
                org.apache.poi.hssf.usermodel.HSSFSheet sheet = workbook.createSheet("用户账单信息");
                
                // 创建表头
                org.apache.poi.hssf.usermodel.HSSFRow row = sheet.createRow(0);
                row.createCell(0).setCellValue("电话卡账单联表");
                row.createCell(1).setCellValue("账单表id");
                row.createCell(2).setCellValue("客户id");
                row.createCell(3).setCellValue("手机号");
                row.createCell(4).setCellValue("用户姓名");
                
                workbook.write(response.getOutputStream());
                workbook.close();
                response.flushBuffer();
            } catch (Exception ex) {
                log.error("创建简单Excel文件失败", ex);
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/plain");
                    response.getWriter().write("导出Excel文件失败: " + e.getMessage() + "; " + ex.getMessage());
                } catch (Exception exc) {
                    log.error("设置错误响应失败", exc);
                }
            }
        }
    }
    
    @ApiOperation(value = "导出用户账单表结构信息", notes = "导出用户账单表结构信息")
    @PostMapping("/exportTableStructure")
    public void exportTableStructure(HttpServletResponse response) {
        try {
            // 导出用户账单表结构信息
            tableStructureExportUtils.exportTableStructureToExcel("phone_bill", response);
        } catch (Exception e) {
            log.error("导出用户账单表结构信息失败", e);
            // 设置错误响应
            try {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/plain");
                response.getWriter().write("导出表结构信息失败: " + e.getMessage());
            } catch (Exception ex) {
                log.error("设置错误响应失败", ex);
            }
        }
    }
}
